<template>
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.name" placeholder="平台名称" style="width: 150px; margin-right: 15px" clearable />
        <!-- <SelectOption :options="data.orgAllList" :placeholder="'承建单位'" @change-value="changeValue"> </SelectOption> -->
        <div class="conUnitName">
          <el-cascader popper-class="gy-cascader" :options="data.orgAllList" :props="data.popupTreeProps"
            v-model="data.params.conUnit" :show-all-levels="false" placeholder="承建单位" clearable>
            <template #default="{ data }">
              <el-tooltip :disabled="data.name.length < 13" class="item" effect="dark" :content="data.name"
                placement="bottom-start">
                <span>{{ data.name }}</span>
              </el-tooltip>
            </template>
          </el-cascader>
        </div>

        <SelectOption :options="data.levelOptions" :placeholder="'平台级别'" @change-value="changeValue1"> </SelectOption>
        <SelectOption :options="data.typeOptions" :selectValue="data.typeValue" :placeholder="'专业类别'"
          @change-value="changeValue2"> </SelectOption>
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:PTJCJS:GDYFPT:UNLOCK'">解锁</el-button>
        <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:PTJCJS:GDYFPT:LOCK'">锁定</el-button>
        <el-button class="ordinary" @click="getExportBtn()" v-limit="'KJSL:PTJCJS:GDYFPT:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'KJSL:PTJCJS:GDYFPT:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'KJSL:PTJCJS:GDYFPT:ADD'">新增</el-button>
      </el-col>
    </el-row>

    <div>
      <Table :loading="data.isLoading" :tableArr="data.allTableData" :pagination="data.page" :columns="data.columns"
        :total="data.page.total" @selectItem="getCurrentList" @delectTable="delectIds" @currentChange="currentChange"
        @sizeChange="sizeChange">

        <template #operate="{ row }">
          <el-button size="small" class="ordinary" :key="row.id + 'bj'" v-show="row.updateFlag"
            :disabled="row.isLock == 1" v-limit="'KJSL:PTJCJS:GDYFPT:EDIT'" @click="handleEdit(row)">编辑 </el-button>
          <el-button size="small" class="ordinary" :key="row.id + 'bj'" @click="handleDetail(row)">详情</el-button>
          <el-button v-if="row.status == '待确认'" size="small" type="primary" :key="row.id + 'qr'"
            v-limit="'KJSL:PTJCJS:GDYFPT:CONFIRM'" :disabled="row.isLock == 1"
            @click="handleConfirm(row)">确认</el-button>
        </template>
      </Table>
    </div>

    <!--新增、修改、确认弹框-->
    <el-dialog v-model="data.dialogVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false"
      destroy-on-close>

      <template #title>
        <div class="my-header" v-loading="data.detail_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Information ref="getAssociation" v-if="data.dialogVisible" @valueFlag="valueFlag"></Information>
            </el-tab-pane>
            <el-tab-pane label="平台成员" name="2">
              <Members :members="data.members" @dataChange="dataChange" @paramsChange="paramsChange"></Members>
            </el-tab-pane>
            <!--            <el-tab-pane label="平台项目" name="3">
              <Association :projects="data.projects" @dataChange="dataChange" @projectParams="projectParams">
              </Association>
            </el-tab-pane>-->
            <el-tab-pane label="平台项目" name="3"><!-- //下拉选项目-->
              <Associationxiangmu :projects="data.projects" @dataChange="dataChange" @projectParams="projectParams">
              </Associationxiangmu>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="4">
              <platformFiles :files="data.files" @dataChange="dataChange" @filesParams="filesParams"
                download="KJSL:PTJCJS:GDYFPT:DOWNLOAD" upload="KJSL:PTJCJS:GDYFPT:UPLOAD"
                fileDelete="KJSL:PTJCJS:GDYFPT:FILEDELETE"></platformFiles>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="5" v-if="data.addFlag == 1">
              <record :changeLogs="data.changeLogs"></record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <!--详情-->
    <el-dialog v-model="data.detailVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false"
      destroy-on-close>

      <template #title>
        <div class="my-header" v-loading="data.detailVisible_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Informationxq ref="getAssociation" v-if="data.detailVisible" @valueFlag="valueFlag"></Informationxq>
            </el-tab-pane>
            <el-tab-pane label="平台成员" name="2">
              <Membersxq :members="data.members" @dataChange="dataChange" @paramsChange="paramsChange"></Membersxq>
            </el-tab-pane>
            <el-tab-pane label="平台项目" name="3">
              <Associationxq :projects="data.projects" @dataChange="dataChange" @projectParams="projectParams">
              </Associationxq>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="4">
              <platformFilesxq :files="data.files" @dataChange="dataChange" @filesParams="filesParams"
                download="KJSL:PTJCJS:GDYFPT:DOWNLOAD" upload="KJSL:PTJCJS:GDYFPT:UPLOAD"
                fileDelete="KJSL:PTJCJS:GDYFPT:FILEDELETE"></platformFilesxq>
            </el-tab-pane>
            <el-tab-pane label="变更记录" name="5" v-if="data.addFlag == 1">
              <record :changeLogs="data.changeLogs"></record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>

        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import Association from '@/views/science/components/association/association.vue'
import Associationxq from '@/views/science/components/association/associationxq.vue'
import Members from '@/views/science/components/members/members.vue'
import Membersxq from '@/views/science/components/members/membersxq.vue'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue'
import platformFilesxq from '@/views/science/components/platformFiles/platformFilesxq.vue'
import record from '@/views/science/components/record/record.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals, tips } from '@/views/science/components/tips/tips'
import Information from '@/views/science/construction/high-end-platform/information.vue'
import Informationxq from '@/views/science/construction/high-end-platform/informationxq.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { useStore } from 'vuex'

import {
  getAdd,
  getConfirm,
  getDelect,
  getDetail,
  getExport,
  getList,
  getLock,
  getUnlock,
  getUpdate
} from '../../api/hignEnd'
import tableData from './tableHeader.json'
import { getDetailById } from "@/views/project/api/projectApplication";
import Associationxiangmu from "@/views/science/components/association/associationxiangmu.vue";
import { ElMessage } from "element-plus"
export default {
  // directives: {
  //     limit: hasDirective,
  //   },
  components: {
    Associationxiangmu,
    SelectOption,
    Table,
    Information,
    Informationxq,
    Members,
    Membersxq,
    Association,
    Associationxq,
    platformFiles,
    platformFilesxq,
    record,
    PopupTreeInput,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const data = reactive({
      addFlag: 0,
      unit: [],
      dialogVisible: false,
      recordShow: false,
      isLoading: false,
      detail_loading: false,
      detailVisible_loading: false,
      detailVisible: false,
      page: { page: 1, limit: 10, total: 0 },
      params: {
        name: '',
        conUnit: [],
        level: '',
        proType: "",
        current: 1,
        size: 10,
      },
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },
      deptForm: {
        parentId: 0,
        parentName: '',
      },

      selectedRows: [] as any,
      columns: tableData.platformTableHeader,
      ids: [],
      allTableData: [],
      // orgAllList: computed(() => store.state.technologyStrength.orgAllList),
      orgAllList: [],
      levelOptions: computed(() => store.state.technologyStrength.gdlevelSelect),
      typeOptions: [],
      typeValue: '',
      members: [
      ],
      projects: [
      ],
      files: [
      ],
      changeLogs: [
      ],

      flag: null,
    })
    const changeValue = (item) => {
      (data.params.conUnit = item.id)
    }
    const changeValue1 = (item) => {
      if (item) {
        data.params.level = item.itemValue
      } else {
        data.params.level = ''
      }
      data.typeOptions = item.children
      data.params.proType = ''
      data.typeValue = ''
    }

    const changeValue2 = (item) => {
      data.params.proType = item.itemValue
      data.typeValue = item.itemText
    }

    //主页面表格初始化
    const tableList = async () => {
      data.isLoading = true
      // data.params.conUnit = data.params.conUnit[0]
      let obj = { ...data.params } as any

      obj.conUnit = obj.conUnit ? obj.conUnit[obj.conUnit.length - 1] : ''
      let res = await getList(obj)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          if (item.status == 0) {
            item.status = "待确认"
          } else {
            item.status = "已确认"
          }
        })
        data.allTableData = res.data.data.records
        data.page.total = records.total
        data.isLoading = false
      } else {
        data.isLoading = false
      }
    }

    //详情数据获取
    const detailData = async (id) => {
      data.dialogVisible = true
      data.detail_loading = true
      let res = await getDetail(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technologyStrength/getForm', { ...arr })
        data.members = res.data.data.members
        data.projects = res.data.data.projects
        data.files = res.data.data.files
        data.changeLogs = res.data.data.changeLogs
        data.addFlag = 1
        data.detail_loading = false
      } else {
        data.detail_loading = false
      }

    }

    //详情数据获取
    const detailVisibleData = async (id) => {
      data.detailVisible = true
      data.detailVisible_loading = true
      let res = await getDetail(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technologyStrength/getForm', { ...arr })
        data.members = res.data.data.members
        data.projects = res.data.data.projects
        data.files = res.data.data.files
        data.changeLogs = res.data.data.changeLogs
        data.addFlag = 1
        data.detailVisible_loading = false
      } else {
        data.detailVisible_loading = false
      }

    }
    const handleDetail = (row) => {
      detailVisibleData(row.id)
      store.commit('technologyStrength/getRowId', row.id)
    }

    const handleClose = () => {
      data.detailVisible = false
      data.recordShow = false
      activeName.value = '1'
      store.commit('technologyStrength/emptyForm')
    }


    const dataChange = () => {
      detailData(store.state.technologyStrength.rowId)
    }

    const paramsChange = (params) => {
      data.members = params
    }

    const projectParams = (params) => {
      data.projects = params
    }

    const filesParams = (params) => {
      data.files = params
    }

    // 点击查询按键，分页设置为当前页为1，
    const search = () => {
      data.page.page = 1
      console.log(data.params)
      tableList()
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    const delectIds = (ids) => {
      data.ids = ids
    }

    const currentChange = (current) => {
      console.log(current, '123123')
      data.params.current = current
      tableList()
    }

    const sizeChange = (size) => {
      console.log(size)
      data.params.size = size
      tableList()
    }

    const handleDetect = async () => {
      if (data.ids.length) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let res = await getDelect(data.ids)
          if (res.data.success) {
            tips(res.data.msg, 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }

    const getLockBtn = async () => {
      if (data.ids.length == 1) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '待确认') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals('是否锁定选择内容', '提示', 'warning').then(async () => {
          let res = await getLock(data.ids)
          if (res.data.success) {
            tips(res.data.msg, 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else if (data.ids.length == 0) {
        tips('请选择', 'warning')
      } else {
        tips('锁定功能不可批量操作', 'warning')
      }
    }
    const getUnlockBtn = async () => {
      if (data.ids.length == 1) {
        Modals('是否解锁选择内容', '提示', 'warning').then(async () => {
          let res = await getUnlock(data.ids)
          if (res.data.success) {
            tips(res.data.msg, 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else if (data.ids.length == 0) {
        tips('请选择', 'warning')
      } else {
        tips('解锁功能不可批量操作', 'warning')
      }
    }

    const getExportBtn = async () => {
      let msg = '是否导出全部数据'
      if (data.ids.length > 0) {
        msg = '是否导出所选数据'
      }
      Modals(msg, '提示', 'warning').then(async () => {
        let obj = { ...data.params } as any
        obj.conUnit = obj.conUnit ? obj.conUnit[obj.conUnit.length - 1] : ''

        const params = {
          ...obj,
          ids: data.ids
        }
        await getExport(params, "高端研发平台")
      }).catch(() => {
        console.log("点击了取消")
      })
    }

    const handleAdd = () => {
      data.dialogVisible = true
      data.addFlag = 0
      data.members = []
      data.projects = []
      data.files = []
      store.commit('technologyStrength/emptyForm')
    }
    const handleEdit = (row) => {
      detailData(row.id)
      store.commit('technologyStrength/getRowId', row.id)
    }

    const handleConfirm = async (row) => {
      Modals('是否确认当前流程', '提示', 'warning').then(async () => {
        let res = await getConfirm(row.id)
        if (res.data.success) {
          tableList()
        }
      }).catch(() => {
        console.log("点击了取消")
      })

    }

    const valueFlag = (flag) => {
      data.flag = flag
    }

    const getAssociation = ref()
    const handleSave = async () => {
      const form = store.state.technologyStrength.form
      getAssociation.value.submitForm()
      if (!data.flag) {
        return tips('请将基本信息补充完整', 'warning')
      }
      // if (!validatePhoneNumber(form.phone)) {
      //   tips('联系电话格式不正确！', 'warning')
      //   return false
      // }
      const params = {
        baseInfo: form,
        memberList: data.members,
        fileList: data.files,
        projectList: data.projects
      }
      let res
      if (data.addFlag == 0) {
        res = await getAdd(params)
      } else {
        res = await getUpdate(params)
      }
      if (res.data.success) {
        tableList()
        handleCloseDialog()
      }
    }

    const handleCloseDialog = () => {
      data.dialogVisible = false
      data.recordShow = false
      activeName.value = '1'
      store.commit('technologyStrength/emptyForm')
    }
    const getOrgList = () => {
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        console.log('getOrgList', res);
        data.orgAllList = res.data.data
      })
    }

    onMounted(() => {
      getOrgList()
    })
    tableList()

    return {
      data,
      activeName,
      store,
      getAssociation,
      valueFlag,
      getLockBtn,
      getUnlockBtn,
      getExportBtn,
      changeValue,
      changeValue1,
      changeValue2,
      dataChange,
      paramsChange,
      projectParams,
      filesParams,
      currentChange,
      sizeChange,
      // beforeActive,
      getCurrentList,
      delectIds,
      handleDetect,
      handleAdd,
      handleEdit,
      handleConfirm,
      search,
      handleSave,
      handleCloseDialog,
      handleDetail, //详情
      handleClose, //详情
    }
  },
}
</script>

<style lang="scss">
.conUnitName {
  display: inline-block;
  width: 200px;
  margin-right: 15px;
}

.gy-cascader {
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>

<style lang="scss" scoped>
.container {
  background-color: white !important;
  padding: 20px;
}

// :deep(.el-dialog__body) {
//   padding: 0 !important
// }
:global(.el-dialog__body) {
  padding: 0;
}

.dialogCloseBtn {
  position: absolute;
  top: 20px;
  right: 20px;
}

// .el-col {
//   line-height: 60px;
// }

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

:deep(.demo-tabs > .el-tabs__content) {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

:deep(.demo-tabs > .el-tabs__content::-webkit-scrollbar) {
  display: none;
  /* Chrome Safari */
}

:deep .el-dialog__header {
  overflow-y: scroll;
}
</style>
